import React, { Component, Fragment } from 'react';
import { Input, message } from 'antd';
import styles from './index.less';
import Eject from '@/components/Eject';
import * as apis from '@/services/SystemMgr';

export default class AddRole extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      values: {
        roleName: this.props.roleName,
        roleDesc: this.props.roleDesc,
      },
    };
  }

  componentWillReceiveProps(newProps) {
    const { values } = this.state;
    values.roleName = newProps.roleName;
    values.roleDesc = newProps.roleDesc;
    this.setState({
      values,
    });
  }

  // 点击弹出
  handleShowDrawer = () => {
    this.setState({
      visible: true,
    });
  };

  // 点击收起
  handleOnClose = () => {
    this.setState({
      visible: false,
    });
  };

  // 获取用户输入的角色名称和角色描述
  handleNameIptChange = e => {
    const { values } = this.state;
    const key = e.target.name;
    values[key] = e.target.value;
    this.setState({
      values,
    });
  };

  // 新增--编辑  角色
  handleOkBtnClick = async () => {
    const { values } = this.state;
    const params = values;
    if (!params.roleName || !params.roleDesc) {
      message.warning('输入为空！');
    } else {
      if (this.props.value === '新增角色') {
        const data = await apis.createRoleUsingPOST({ data: params });
        if (data.code === 1) {
          this.setState({
            values: {
              roleName: '',
              roleDesc: '',
            },
          });
          message.success('添加成功!');
        }
      } else {
        params.roleId = this.props.roleId;
        const data = await apis.updateRoleUsingPUT({ data: params });
        if (data.code === 1) {
          this.setState({
            values: {
              roleName: '',
              roleDesc: '',
            },
          });
        }
        message.success('编辑成功!');
      }
      this.handleOnClose();
      this.props.update();
    }
  };

  render() {
    return (
      <Eject
        btnType={this.props.btnType}
        value={this.props.value}
        title={this.props.title}
        width={546}
        showDrawer={this.handleShowDrawer}
        handleOkBtnClick={this.handleOkBtnClick}
        onClose={this.handleOnClose}
        visible={this.state.visible}
        modelJsx={
          <div className={styles['add-role']}>
            <span>角色名称:</span>
            <Input
              placeholder="输入角色名称"
              width={200}
              name="roleName"
              value={this.state.values.roleName}
              onChange={e => this.handleNameIptChange(e)}
            />
            <span>角色描述:</span>
            <Input.TextArea
              rows={4}
              placeholder="输入角色描述"
              name="roleDesc"
              value={this.state.values.roleDesc}
              onChange={e => this.handleNameIptChange(e)}
            />
          </div>
        }
      />
    );
  }
}
